package com.test.many.very_much.provider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.test.many.very_much.dto.AccessTokenDTO;
import com.test.many.very_much.dto.GiteeUser;
import com.test.many.very_much.dto.GithubUser;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
* @Description:    Github支持（第三方提供者）
* @Author:         Joe
* @CreateDate:     2020/4/2 17:26
*/
@Component
@Slf4j
public class GithubProvider {

    /**
     * 获取access_token
     * 将此交换code为访问令牌
     * @param accessTokenDTO
     * @return
     */
    public String getAccessToken(AccessTokenDTO accessTokenDTO){
        log.info("accessTokenDTO{}"+accessTokenDTO);
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenDTO));
        Request request = new Request.Builder()
                .addHeader("Accept","application/json")
                .url("https://github.com/login/oauth/access_token")
                .post(body)
                .build();
        log.info("发送的请求信息{}"+request);
        try (Response response = client.newCall(request).execute()) {
            String string =response.body().string();
            log.info("string:{}"+string);
            JSONObject jsonObject = JSONObject.parseObject(string);
            log.info("jsonObject"+jsonObject);
            String access_token = jsonObject.get("access_token").toString();
            return access_token;
        } catch (IOException e) {
        }
        return null;
    }

    /**
     * 获取用户数据
     * 使用访问令牌访问API
     * @param accessToken
     * @return
     */
    public GithubUser getUser(String accessToken){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://api.github.com/user?access_token="+accessToken)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String string =response.body().string();
            GithubUser githubUser = JSON.parseObject(string, GithubUser.class);
            return githubUser;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
